package spring.webmvc;

import spring.annotations.ContextParam;
import spring.annotations.Import;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.Objects;

public class ContextLoaderListener extends ContextLoader implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        boolean isSelect = false;
        ContextParam param = this.getClass().getAnnotation(ContextParam.class);
        if (Objects.nonNull(param)) {
            ServletContext servletContext = sce.getServletContext();
            servletContext.setInitParameter(param.name(), param.value());
            isSelect = true;
        }
        if (!isSelect) {
            Import configClass = this.getClass().getAnnotation(Import.class);
            if (Objects.nonNull(configClass) && configClass.value().length > 0) {
                ServletContext servletContext = sce.getServletContext();
                servletContext.setInitParameter(ANNOTATION_NAME, configClass.value()[0].getName());
                isSelect = true;
            }
        }
        if (!isSelect) {
            throw new IllegalArgumentException("请选择一种有效的项目初始化方式，否则项目无法正确加载。");
        }
        initWebApplicationContext(sce.getServletContext());
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        closeWebApplicationContext(sce.getServletContext());
    }


}
